import * as THREE from 'three';
import {MoveDirectionControls} from '../../js/MoveDirectionControls.js'
import Stats from 'three/examples/jsm/libs/stats.module.js';

import {baseUrl} from '../../js/base.js'
import '../../css/base.css'
import {TWEEN} from "three/examples/jsm/libs/tween.module.min.js";
import request from "../../test/js/request";
// import IndexDB from "../../js/IndexDB";
// let count = 0
// setInterval(() => {
//     const aa = "{isSHowPano: 'iframeIsShow'}" + ++count
//     console.log('aa: ', aa)
//     window.parent.postMessage(JSON.stringify(aa), '*') //发送消息
// }, 1000)
// window.addEventListener('message', (event) => {
//     if (event && event.data) {
//         let data = event.data
//         try {
//             data = JSON.parse(event.data)
//         } catch (e) {
//             console.warn(`JSON.parse Error: ${e}, data = ${data}`)
//         }
//         if (data.isRendering && typeof data.isRendering.state === 'boolean') this.isRendering = data.isRendering.state
//         if (data.isShowPano && typeof data.isShowPano.state === 'boolean') this.iframeIsShow = data.isShowPano.state
//     }
// }, false)

let canvas = document.getElementById("canvas")
let renderer, scene, camera;
let moveDirectionControls;

let peopleH = 1.8
let cameraP = new THREE.Vector3(0, peopleH, 20);

let mouseStart = new THREE.Vector2(), mouse = new THREE.Vector2(), cursor = null;
let raycaster = new THREE.Raycaster();
let startEuler = new THREE.Euler();
let intersectObjects

THREE.Vector2.prototype.equalsToFixed = function (v, decimalPoint) {
    return ((+v.x.toFixed(decimalPoint) === +this.x.toFixed(decimalPoint)) &&
        (+v.y.toFixed(decimalPoint) === +this.y.toFixed(decimalPoint)));
}
const stats = new Stats()
document.body.appendChild(stats.domElement)

async function initCSR() {
    const w = canvas.offsetWidth || window.innerWidth;
    const h = canvas.offsetHeight || window.innerHeight;

    camera = new THREE.PerspectiveCamera(75, w / h, 0.1, 10000)
    camera.position.copy(cameraP)
    cameraP = camera.position

    scene = new THREE.Scene()

    renderer = new THREE.WebGLRenderer({canvas, antialias: true, alpha: true});
    camera.updateProjectionMatrix();
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(w, h, false)

    // const id = 1
    // const db = await IndexDB.openDB('editorDB', 'firstModel', 1)
    // const dataByKey = await IndexDB.getDataByKey(db, 'firstModel', id)
    // console.log('dataByKey2', dataByKey)
    // if (!dataByKey) {
    //     IndexDB.addData(db, 'firstModel', {
    //         id,
    //         value: 'aaa'
    //     })
    // }
}

function initLight() {
    const ambientLight = new THREE.AmbientLight(0xffffff, .2);
    scene.add(ambientLight)

    const hemisphereLight = new THREE.HemisphereLight(0xaaaaaa, .5);
    scene.add(hemisphereLight)

    const directionalLight = new THREE.DirectionalLight(0xFFFFFF, 1);
    directionalLight.position.set(1, 1, 1)
    scene.add(directionalLight)
}

function initModel() {
    let textureLoader = new THREE.TextureLoader();
    let texture = textureLoader.load(require('../../../static/images/floor.jpeg'))
    texture.wrapS = texture.wrapT = THREE.MirroredRepeatWrapping
    texture.repeat.set(32, 32)
    texture.anisotropy = 8
    const geometry = new THREE.PlaneGeometry(100, 100, 100);
    const material = new THREE.MeshPhongMaterial({color: 0x909399, map: texture, side: THREE.DoubleSide});

    const floor = new THREE.Mesh(geometry, material);
    floor.name = 'floor'
    geometry.rotateX(Math.PI / 2)
    scene.add(floor);

    const cursorTexture = textureLoader.load(require('../../../static/images/pointer.png'))
    const meshBasicMaterial = new THREE.MeshBasicMaterial({map: cursorTexture, depthTest: false, transparent: true, opacity: .8, side: THREE.DoubleSide});
    const planeGeometry = new THREE.PlaneGeometry();
    planeGeometry.rotateX(Math.PI / 2)
    cursor = new THREE.Mesh(planeGeometry, meshBasicMaterial)
    cursor.name = 'floor'
    floor.add(cursor)

    const geometryBox = new THREE.BoxBufferGeometry(2, 2, 2);

    for (let i = 0; i < 500; i++) {
        const materialBox = new THREE.MeshPhongMaterial(
            {color: new THREE.Color(Math.random(), Math.random(), Math.random())});
        const meshBox = new THREE.Mesh(geometryBox, materialBox);
        meshBox.name = 'hot_' + i
        meshBox.position.set(
            Math.round(Math.random() * 60) - 30,
            Math.round(Math.random() * 30) + 1,
            Math.round(Math.random() * 60) - 30
        )
        scene.add(meshBox);
    }

}

function initControls() {
    moveDirectionControls = new MoveDirectionControls(camera, canvas);

    function getIntersectObjects() {
        raycaster.setFromCamera(mouse, camera);
        intersectObjects = raycaster.intersectObjects(scene.children, true);
    }

    moveDirectionControls.startFun = function (e) {
        mouse.copy(moveDirectionControls.getPointer())
        mouseStart.copy(mouse)
        startEuler.copy(moveDirectionControls.getObject().rotation)
    }
    moveDirectionControls.moveFun = function (e) {
        mouse.copy(moveDirectionControls.getPointer())
        getIntersectObjects()
        if (intersectObjects.length && intersectObjects[0].object.name === 'floor') {
            cursor.material.visible = true
            cursor.position.copy(intersectObjects[0].point)
        } else {
            cursor.material.visible = false
        }
    }

    moveDirectionControls.endFun = function (e) {
        mouse.copy(moveDirectionControls.getPointer())
        getIntersectObjects()
        if (mouseStart.equalsToFixed(mouse, 2)) {
            if (intersectObjects.length && intersectObjects[0].object.name === 'floor') {
                const to = intersectObjects[0].point.clone().add(new THREE.Vector3(0, peopleH, 0))
                moveDirectionControls.fromMoveTo({to})
            } else if (intersectObjects.length && intersectObjects[0].object.name.indexOf('hot') > -1) {
                confirm(`你点击了模型: ${intersectObjects[0].object.name}`)
            }
        }
        if (intersectObjects.length && intersectObjects[0].object.name === 'floor') {
            cursor.material.visible = true
            cursor.position.copy(intersectObjects[0].point)
        } else {
            cursor.material.visible = false
        }
    }
}

function onWindowResize() {
    const width = canvas.offsetWidth;
    const height = canvas.offsetHeight;
    camera.aspect = width / height;
    renderer.setSize(width, height, false);
    camera.updateProjectionMatrix();
} // 控制窗口大小

function render() {
    if (moveDirectionControls) moveDirectionControls.update();
    if (TWEEN) TWEEN.update()
    renderer.render(scene, camera)
    stats.update();
}

function animation() {
    requestAnimationFrame(animation)
    render()
}

(async () => {
    initCSR();
    initLight();
    initModel();
    initControls();
    animation();
    window.addEventListener('resize', onWindowResize);
    setInterval(() => {
        // console.log(camera.position);
        // console.log(moveDirectionControls.getPosition())
        // console.log(camera.position.equals(moveDirectionControls.getPosition()))
        // console.log(moveDirectionControls.getDirection())
    }, 2000)
})();

// import VConsole from  'vconsole'
// window.vConsole = new VConsole({
//   defaultPlugins: ['system', 'network', 'element', 'storage'], // 可以在此设定要默认加载的面板
//   maxLogNumber: 1000,
//   // disableLogScrolling: true,
//   onReady: () => {
//     console.log('vConsole is ready.');
//   },
//   onClearLog: () => {
//     console.log('on clearLog');
//   }
// });

